package com.zzw.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.zzw.model.UserFace;
import com.zzw.model.UserFaceCheck;
import com.zzw.service.MyFaceEngine;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@RestController
@RequestMapping("/face-api/face")
public class FaceController {
    @Resource
    private MyFaceEngine myFaceEngine;
    @Resource
    private HashOperations<String, String, byte[]> hashOperations;

    /**
     * 采集人脸
     *
     * @param userFace 用户脸
     * @return {@link Integer}
     */
    @PostMapping("/upload")
    public Integer upload(@RequestBody UserFace userFace) {
        String base64 = userFace.getFaceImg();
        String[] dataArray = StrUtil.splitToArray(base64, "base64,");
        byte[] bytes = Base64.decode(dataArray[1]);
        byte[] feature = myFaceEngine.getFeature(bytes);
        String hashKey = "venue." + userFace.getVenueId();
        String key = userFace.getId();
        hashOperations.put(hashKey, key, feature);
        return 1;
    }

    /**
     * 校验人脸
     *
     * @param userFaceCheck 用户面检查
     * @return float
     */
    @PostMapping("/check")
    public String check(@RequestBody UserFaceCheck userFaceCheck) {
        String base64 = userFaceCheck.getFaceImg();
        String[] dataArray = StrUtil.splitToArray(base64, "base64,");
        byte[] bytes = Base64.decode(dataArray[1]);
        String hashKey = "venue." + userFaceCheck.getVenueId();
        Map<String, byte[]> entries = hashOperations.entries(hashKey);
        float score = 0;
        for (Map.Entry<String, byte[]> entry : entries.entrySet()) {
            score = myFaceEngine.compare(bytes, entry.getValue());
            if (score >= 0.90)
                return "人脸通过";
        }
        return "查无此人";
    }
}
